package com.hddz.comlib.packet;

import java.nio.ByteBuffer;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import android.util.Log;

import com.hddz.comlib.model.Sensor;
import com.hddz.comlib.util.ConvertUtility;

/**
 * 历史数据包
 * 
 * @author hddz
 * 
 */
public class HistoryPacket extends Packet {
	private final String TAG = "HistoryPacket"; 
	private SimpleDateFormat dateformat = new SimpleDateFormat("yyMMdd HHmm");
	private Calendar cal = Calendar.getInstance();
	/**
	 * 站号
	 */
	private int stationId;

	/**
	 * 起始时间
	 */
	private Date startTime;

	private Date nextStartTime;

	/**
	 * 拆分实时数据包
	 */
	private List<RealTimePacket> realTimePackets = new ArrayList<RealTimePacket>();
	/**
	 * 包括
	 */
	private List<Sensor> sensors = new ArrayList<Sensor>();

	public int getStationId() {
		return stationId;
	}

	public void setStationId(int stationId) {
		this.stationId = stationId;
	}

	public Date getStartTime() {
		return startTime;
	}

	public void setStartTime(Date startTime) {
		this.startTime = startTime;
	}

	public List<RealTimePacket> getRealTimePackets() {
		return realTimePackets;
	}

	public List<Sensor> getSensors() {
		return sensors;
	}

	public Date getNextStartTime() {
		return nextStartTime;
	}

	public void setNextStartTime(Date nextStartTime) {
		this.nextStartTime = nextStartTime;
	}

	private int getMinite(int sourc) {
		switch (sourc) {
		case 0x43:
			return 1;
		case 0x44:
			return 5;
		case 0x45:
			return 10;
		case 0x31:
			return 15;
		case 0x32:
			return 30;
		case 0x33:
			return 60;
		case 0x34:
			return 120;
		case 0x35:
			return 240;
		case 0x36:
			return 360;
		case 0x37:
			return 720;
		case 0x38:
			return 1440;
		default:
			return 0;
		}
	}

	@Override
	public String createViewText() {
		// TODO Auto-generated method stub
		StringBuilder sb = new StringBuilder();
		sb.append("站号:" + this.stationId);
		sb.append("起始时间:" + dateformat.format(this.startTime));
		sb.append("\r\n");
		for (RealTimePacket r : this.realTimePackets) {
			sb.append("时间:" + dateformat.format(r.sendTime));
			sb.append("\r\n");
			for (Sensor s : r.getSensors()) {

				sb.append("通道:" + s.getChannel());
				sb.append(" 值 :" + s.getValue());
				sb.append(" | ");
			}
			sb.append("\r\n");
		}
		return sb.toString();
	}

	@Override
	public Boolean parse(ByteBuffer data, int len) {
		// TODO Auto-generated method stub
		byte[] b = new byte[len];
		int perPosition = data.position();
		try {
			data.get(b, 0, len);
			this.sourceText = ConvertUtility.bystesToStr(b, 0, len);
			Log.d(TAG, this.sourceText);
			data.position(perPosition);
			Sensor sensor = null;
			stationId = ((data.get() & 0xff) * 256 + (data.get() & 0xff)) * 256 + (data.get() & 0xff);
			startTime = dateformat.parse(String.format("%02d", ConvertUtility.BCDToInt(data.get() & 0xff)) + String.format("%02d", ConvertUtility.BCDToInt(data.get() & 0xff))
					+ String.format("%02d", ConvertUtility.BCDToInt(data.get() & 0xff)) + " " + String.format("%02d", ConvertUtility.BCDToInt(data.get() & 0xff))
					+ String.format("%02d", ConvertUtility.BCDToInt(data.get() & 0xff)));
			int count = data.get() & 0xff;
			int interval = getMinite(data.get() & 0xff);
			sensor = new Sensor();
			sensor.setStationId(stationId);
			sensor.setChannel("V");
			sensor.setValue(((data.get() & 0xff) * 2) / 100.0);// 电池电压解数据时，先乘以2，再除以100
			// 原来的解法 (data[index] * 256 + data[index + 1]) /
			// 100.0;//电池电压解数据时，除以100；

			cal.setTime(startTime);
			for (int i = 0; i < count; i++) {
				RealTimePacket r = new RealTimePacket();
				r.setSendTime(cal.getTime());
				r.setSendTimes(dateformat.format(cal.getTime()));
				r.getSensors().add(sensor);
				realTimePackets.add(r);
				cal.add(Calendar.MINUTE, interval);
			}
			nextStartTime = cal.getTime();
			while (data.position() < perPosition + len) {
				int no_flag = data.get() & 0xff;
				int no = no_flag % 16;
				int flag = no_flag / 16;
				switch (flag) {
				case 1:// 脉冲量 累计流量 P 在上一时刻流量的基础上增加的量（最高位0表示正数，1表示负数）
					sensor = new Sensor();
					sensor.setStationId(stationId);
					sensor.setChannel("P" + no);
					int perValue = (data.get() & 0xff) * 1000000 + (data.get() & 0xff) * 10000 + (data.get() & 0xff) * 100 + (data.get() & 0xff);
					sensor.setValue(perValue);
					realTimePackets.get(0).getSensors().add(sensor);
					for (int i = 1; i < count; i++) {
						int value = data.get() & 0xff;
						sensor = new Sensor();
						sensor.setStationId(stationId);
						sensor.setChannel("P" + no);
						if (value < 0) {
							sensor.setValue(perValue - ((0 - value) * 256 + (data.get() & 0xff)));
						} else {
							sensor.setValue(perValue + value * 256 + (data.get() & 0xff));
						}
						perValue = (int) sensor.getValue();
						realTimePackets.get(i).getSensors().add(sensor);
					}
					break;
				case 2:// 开关量 K
					sensor = new Sensor();
					sensor.setStationId(stationId);
					sensor.setChannel("K" + no);
					sensor.setValue((data.get() & 0xff) - 0x30);
					for (int i = 0; i < count; i++) {
						realTimePackets.get(i).getSensors().add(sensor);
					}
					break;
				case 3:// 模拟量 A
					for (int i = 0; i < count; i++) {
						sensor = new Sensor();
						sensor.setStationId(stationId);
						sensor.setChannel("A" + no);
						sensor.setValue(((data.get() & 0xff) * 256 + (data.get() & 0xff)) / 1000.0);// 模拟量解数据时，除以1000；
						realTimePackets.get(i).getSensors().add(sensor);
					}
					break;
				case 4:// 报警量 B
					sensor = new Sensor();

					sensor.setStationId(stationId);
					sensor.setChannel("B" + no);
					sensor.setValue((data.get() & 0xff) - 0x30);
					sensors.add(sensor);
					for (int i = 0; i < count; i++) {
						realTimePackets.get(i).getSensors().add(sensor);
					}
					break;
				}
			}
			this.viewText = this.createViewText();
			Log.d(TAG, this.viewText);
			return true;
		} catch (Exception e) {
			// CLogger.Write("HistoryPacket Parse Error" + e.Message);
			return false;
		}
	}

	@Override
	public Boolean parse(List<Byte> data, int start, int len) {
		// TODO Auto-generated method stub
		try {
			this.sourceText = ConvertUtility.bystesToStr(data, start - 3, len + 5);
			Sensor sensor = null;
			int index = start;
			stationId = ((data.get(index) & 0xff) * 256 + (data.get(index + 1) & 0xff)) * 256 + (data.get(index + 2) & 0xff);
			index += 3;

			startTime = dateformat.parse(String.format("%02d", ConvertUtility.BCDToInt(data.get(index) & 0xff))
					+ String.format("%02d", ConvertUtility.BCDToInt(data.get(index + 1) & 0xff)) + String.format("%02d", ConvertUtility.BCDToInt(data.get(index + 2) & 0xff)) + " "
					+ String.format("%02d", ConvertUtility.BCDToInt(data.get(index + 3) & 0xff)) + String.format("%02d", ConvertUtility.BCDToInt(data.get(index + 4) & 0xff)));

			index += 5;
			int count = data.get(index) & 0xff;

			index += 1;
			int interval = getMinite(data.get(index) & 0xff);
			index += 1;

			sensor = new Sensor();
			sensor.setStationId(stationId);
			sensor.setChannel("V");
			sensor.setValue(((data.get(index) & 0xff) * 2) / 100.0);// 电池电压解数据时，先乘以2，再除以100
			// 原来的解法 (data[index] * 256 + data[index + 1]) /
			// 100.0;//电池电压解数据时，除以100；

			index += 1;

			for (int i = 0; i < count; i++) {
				RealTimePacket r = new RealTimePacket();
				cal.setTime(startTime);
				cal.add(Calendar.MINUTE, interval * i);
				r.setSendTime(cal.getTime());
				r.getSensors().add(sensor);
				realTimePackets.add(r);
			}

			while (index < start + len) {
				int no = (data.get(index) & 0xff) % 16;
				int flag = (data.get(index) & 0xff) / 16;
				index++;
				switch (flag) {
				case 1:// 脉冲量 累计流量 P 在上一时刻流量的基础上增加的量（最高位0表示正数，1表示负数）
					sensor = new Sensor();
					sensor.setStationId(stationId);
					sensor.setChannel("P" + no);
					int perValue = (data.get(index) & 0xff) * 1000000 + (data.get(index + 1) & 0xff) * 10000 + (data.get(index + 2) & 0xff) * 100 + (data.get(index + 3) & 0xff);
					sensor.setValue(perValue);
					realTimePackets.get(0).getSensors().add(sensor);
					index += 4;
					for (int i = 1; i < count; i++) {
						sensor = new Sensor();
						sensor.setStationId(stationId);
						sensor.setChannel("P" + no);
						if (data.get(index) < 0) {
							sensor.setValue(perValue - ((0 - data.get(index)) * 256 + (data.get(index + 1) & 0xff)));
						} else {
							sensor.setValue(perValue + data.get(index) * 256 + (data.get(index + 1) & 0xff));
						}
						perValue = (int) sensor.getValue();
						realTimePackets.get(i).getSensors().add(sensor);
						index += 2;
					}
					break;
				case 2:// 开关量 K
					sensor = new Sensor();
					sensor.setStationId(stationId);
					sensor.setChannel("K" + no);
					sensor.setValue((data.get(index) & 0xff) - 0x30);
					for (int i = 0; i < count; i++) {
						realTimePackets.get(i).getSensors().add(sensor);
					}
					index++;
					break;
				case 3:// 模拟量 A
					for (int i = 0; i < count; i++) {
						sensor = new Sensor();
						sensor.setStationId(stationId);
						sensor.setChannel("A" + no);
						sensor.setValue(((data.get(index) & 0xff) * 256 + (data.get(index + 1) & 0xff)) / 1000.0);// 模拟量解数据时，除以1000；
						realTimePackets.get(i).getSensors().add(sensor);
						index += 2;
					}
					break;
				case 4:// 报警量 B
					sensor = new Sensor();

					sensor.setStationId(stationId);
					sensor.setChannel("B" + no);
					sensor.setValue((data.get(index) & 0xff) - 0x30);
					sensors.add(sensor);
					for (int i = 0; i < count; i++) {
						realTimePackets.get(i).getSensors().add(sensor);
					}
					index++;
					break;
				}
			}
			this.viewText = this.createViewText();
			return true;
		} catch (Exception e) {
			// CLogger.Write("HistoryPacket Parse Error" + e.Message);
			return false;
		}
	}
}